/* Copyright (c) 2007 John Wells

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */

// Short-cuts
using EntityKeyValuePair = System.Collections.Generic.KeyValuePair<string, object>;

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;



namespace GameLevel
{
    public sealed class Level : IDisposable
    {
        #region Nested Class: Entity
        public class Entity
        {
            public EntityKeyValuePair[] Items;
            public Vector3 Position;
        } 
        #endregion


        

        #region Fields


        /// <summary>Primitives form the walls, floors, and ceilings of the level</summary>
        //internal Primitive[] Primitives;

        /// <summary>Entities are the fixed-position type items such as spark emitters, spawn points, etc</summary>
        public Entity[] Entities;
        public Model[] Geometry;
        public Terrain[] Terrains;
        public GeometryModel[] GeometryModels;
        public LevelModel[] Models;
        public ModelCommand[] ModelCmds;

        public LevelTrigger[] Triggers;

        // Bounding boxes for each brush
        public CollisionBox[] CollisionBoxes;

        // Lightmaps are textures superimposed on the bsp material
        public Texture2D[] Lightmaps;

        // Lightmaps are textures which provide the light direction
        public Texture2D[] LightDirectionMaps;


        // Private variables
        //private GraphicsDevice _device;
        //private VertexBuffer _vertexBuffer;
        //private VertexDeclaration _vertexDeclaration;
        #endregion

        /// <summary>This constructor is meant to be used by the LevelReader class only</summary>
        internal Level(ContentManager manager)
        {
            // Sanity checks
            if (manager == null) throw new ArgumentNullException("manager");

            // Get the graphics service
            IGraphicsDeviceService service = (IGraphicsDeviceService)manager.ServiceProvider.GetService(typeof(IGraphicsDeviceService));

            // TODO: Do I need to tie into the service events here? I think so!
            
            // Define the format of the vertices we'll be using
            //this._vertexDeclaration = new VertexDeclaration(service.GraphicsDevice, BrushVertex.VertexElements);

            // Setup render-state caching
            //this._stateCache = new StateBlock(service.GraphicsDevice);

            // Cache graphics objects
            //this._device = service.GraphicsDevice;
            //this._vertexBuffer = brushVertexBuffer;

            
        }

        #region Methods

        /// <summary>Needs optimizn'</summary>
        public Entity FindEntityByClassname(string classname)
        {
            Entity[] entities = FindEntitiesByClassname(classname);

            if (entities.Length > 0)
                return entities[0];
            else
                return null;
        }

        /// <summary>Needs optimizn'</summary>
        public Entity[] FindEntitiesByClassname(string classname)
        {
            List<Entity> results = new List<Entity>();
            foreach (Entity entity in this.Entities)
                foreach (KeyValuePair<string, object> kvp in entity.Items)
                    if (kvp.Key.ToLower() == "classname" && kvp.Value is string && (kvp.Value as string).ToLower() == classname.ToLower())
                    {
                        results.Add(entity);
                        break;
                    }

            return results.ToArray();
        }

        #endregion

        #region IDisposable Members
        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }
        #endregion
    }
}